import sys
import json
import sqlite3
import paho.mqtt.client as mqtt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QTableWidget, QTableWidgetItem, QMessageBox

# MQTT 服务器配置
MQTT_BROKER = '127.0.0.1'
MQTT_PORT = 1883
MQTT_TOPIC = 'iot/devices/test/baina/00000000/allinone/tx'


class App(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        self.client = self.setup_mqtt_client()
        self.load_data()

    def initUI(self):
        self.setWindowTitle('MQTT Device Controller')
        self.setGeometry(100, 100, 800, 600)
        layout = QVBoxLayout()

        # 创建表格并设置
        self.table = QTableWidget()
        self.table.setColumnCount(1)  # 只有一列显示设备地址
        self.table.setHorizontalHeaderLabels(['Device Address'])
        self.table.clicked.connect(self.table_clicked)
        layout.addWidget(self.table)

        # 按钮，当点击时发送 MQTT 消息
        send_button = QPushButton('Send MQTT Message')
        send_button.clicked.connect(self.send_button_clicked)
        layout.addWidget(send_button)

        self.setLayout(layout)

    def setup_mqtt_client(self):
        # 创建 MQTT 客户端实例并连接
        client = mqtt.Client()
        client.connect(MQTT_BROKER, MQTT_PORT, 60)
        client.loop_start()
        return client

    def load_data(self):
        # 从数据库加载数据
        conn = sqlite3.connect('/Users/tancongyuan/Desktop/sensor_data.db')
        cursor = conn.cursor()
        cursor.execute("SELECT devaddr FROM parsed_sensor_info")
        rows = cursor.fetchall()
        self.table.setRowCount(len(rows))
        for index, (devaddr,) in enumerate(rows):
            self.table.setItem(index, 0, QTableWidgetItem(devaddr))
        conn.close()

    def table_clicked(self, index):
        row = index.row()
        devaddr = self.table.item(row, 0).text()
        self.send_message(devaddr)

    def send_button_clicked(self):
        # 获取当前选中的行
        current_row = self.table.currentRow()
        if current_row != -1:
            devaddr = self.table.item(current_row, 0).text()
            self.send_message(devaddr)

    def send_message(self, devaddr):
        # 构造和发送 MQTT 消息
        message = {
            "task_type": "set_sensor_light",
            "task_id": "194",
            "data": {
                "devaddr_list": [devaddr],  # 从表格获取的设备地址
                "value": "01"  # 红灯常亮
            }
        }
        message_json = json.dumps(message)
        self.client.publish(MQTT_TOPIC, message_json)
        print(f"Sent message: {message_json}")
        QMessageBox.information(self, "Message Sent", f"Sent message to device {devaddr}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    ex.show()
    sys.exit(app.exec_())